package net.kleinhenz.norabase.client;

import net.kleinhenz.norabase.shared.model.Battlegroup;
import net.kleinhenz.norabase.shared.model.Rune;

import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.tab.Tab;
import com.smartgwt.client.widgets.tab.TabSet;

public class BattlegroupTabSet extends TabSet {
	
	public BattlegroupTabSet() {
		super();
		//openTab(-1, "New Battlegroup");
	}
	
	public void openTab(String battlegroupId, String name, String viewState) {
		for (Tab t : getTabs())
			if (((BattlegroupTab)t).getBattlegroup().getId().equals(battlegroupId)) {
				this.selectTab(t);
				return;
			}

		BattlegroupTab tab = new BattlegroupTab(battlegroupId, name, viewState);
		addTab(tab);
	}
	
	public String getCurrentBattlegroupId() {
		return getSelectedTab()==null?null:((BattlegroupTab)getSelectedTab()).getBattlegroup().getId();
	}
	
	public Battlegroup<Rune> getCurrentBattlegroup() {
		return getSelectedTab()==null?null:((BattlegroupTab)getSelectedTab()).getBattlegroup();
	}

	public void closeTab(String battlegroupId) {
		for (Tab t : getTabs())
			if (((BattlegroupTab)t).getBattlegroup().getId().equals(battlegroupId))
				removeTab(t);
	}

	public void setCurrentTabTitle(String title) {
		if (getSelectedTab()!=null)
			getSelectedTab().setTitle(title);
	}
	
	public void addRune(ListGridRecord record) {
		getCurrentGrid().addData(record);
	}

	public void removeRune(ListGridRecord record) {
		getCurrentGrid().removeData(record);
	}

	private ListGrid getCurrentGrid() {
		if (getSelectedTab()==null)
			return null;
		
		Canvas c = getSelectedTab().getPane();
		if (c instanceof ListGrid) 
			return (ListGrid)c;
		else
			throw new RuntimeException("Error: child of tab is not a grid: " + c);			
	}

	public String getViewState() {
		if (getCurrentGrid()!=null)
			return getCurrentGrid().getViewState();
		else
			return null;
	}

	public void setViewState(String viewState) {
		for (Tab t : getTabs()) {
			Canvas c = t.getPane();
			if (c instanceof ListGrid) 
				((ListGrid)c).setViewState(viewState);
			else
				throw new RuntimeException("Error: child of tab is not a grid: " + c);
		}
	}
}
